#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"

static const int g_socket = -1;

using namespace LogModule;

class TcpClient
{
public:
    TcpClient(uint16_t port, std::string &ip)
        : _port(port), _ip(ip), _sockfd(g_socket)
    {

        _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "client create failed\n");
        }

        // 初始化存储 server 端的， ip 和 port的结构体
        bzero(&_server, sizeof(_server));
        _server.sin_family = AF_INET;                     // 网络通信
        _server.sin_port = htons(_port);                  // 将本地序列转为网络序列
        _server.sin_addr.s_addr = inet_addr(_ip.c_str()); //

        // 获取链接
        int n = ::connect(_sockfd, (struct sockaddr *)&_server, sizeof(_server));
        if (n < 0)
        {
            LOG(FATAL, "connect error\n");
        }
        LOG(INFO, "connet success\n");
    }

    void Start()
    {
        while (true)
        {
            std::string message;
            std::cout << "Enter #";
            std::getline(std::cin, message);

            ::write(_sockfd, message.c_str(), message.size());

            char buffer[1024];
            int n = ::read(_sockfd, buffer, sizeof(buffer)-1);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                break;
            }
        }
    }

    ~TcpClient()
    {
        if(_sockfd > 0)
            ::close(_sockfd);
    }

private:
    uint16_t _port;
    std::string _ip;
    int _sockfd;
    struct sockaddr_in _server;
};